<template>
  <!-- 页面模板 -->
  <div class="wrapper">
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>确认您的订单</p>
      <div></div>
    </header>
    <div class="top-ban"></div>

    <section>
      <!-- 体检人信息 -->
      <div class="title">
        <p>体检人信息</p>
      </div>
      <table>
        <tr>
          <td>姓名:</td>
          <td>{{ userData.realName }}</td>
        </tr>
        <tr>
          <td>证件号码:</td>
          <td>{{ userData.identityCard }}</td>
        </tr>
        <tr>
          <td>出生日期:</td>
          <td>{{ formattedBirthday }}</td>
        </tr>
        <tr>
          <td>手机号码:</td>
          <td>{{ userData.userId }}</td>
        </tr>
      </table>

      <!-- 体检日期 -->
      <div class="title">
        <p>体检日期</p>
      </div>
      <table>
        <tr>
          <td>{{ orderDate }}</td>
        </tr>
      </table>

      <!-- 体检机构 -->
      <div class="title">
        <p>体检机构</p>
      </div>
      <table>
        <tr>
          <td colspan="2">{{ hospitalData.name }}</td>
        </tr>
        <tr>
          <td>营业时间:</td>
          <td>{{ hospitalData.businessHours }}</td>
        </tr>
        <tr>
          <td>采血截止:</td>
          <td>{{ hospitalData.deadline }}</td>
        </tr>
        <tr>
          <td>机构电话:</td>
          <td>{{ hospitalData.telephone }}</td>
        </tr>
        <tr>
          <td>机构地址:</td>
          <td>{{ hospitalData.address }}</td>
        </tr>
      </table>

      <!-- 套餐类型 -->
      <div class="title">
        <p>套餐类型</p>
      </div>
      <table>
        <tr>
          <td>{{ setmeal.name }}</td>
        </tr>
      </table>
    </section>



    <!-- 实付款 -->
    <div>
    <div ref="alipayForm"></div>

    <div class="bottom-btn">
      <div class="first">实付款: <span>￥{{ setmeal.price }}</span></div>
      <div class="last" @click="payWithOrderId">确认支付</div>
    </div>

    <div class="bottom-ban"></div>
    <Footer></Footer>
  </div>
  </div>
</template>
<script>
import { getSessionStorage } from '../common.js';
import axios from 'axios';
import Footer from '@/components/Footer.vue';

export default {
  data() {
    return {
      userData: {},
      hospitalData: {},
      setmeal: {},
      formattedBirthday: '',
      orderId: null,
      orderDate: '',
      docId: null  // 添加 docId 属性
    };
  },
  components: {
    Footer
  },
  mounted() {
    this.initializeData();
  },
  methods: {
    async initializeData() {
      try {
        const orderDate = getSessionStorage('selectedDate');
        const user = getSessionStorage('user');
        const hpId = getSessionStorage('selectedHospitalId');
        const smId = getSessionStorage('selectedSetmealId');
        const docId = getSessionStorage('selectedDoctorId'); // 获取存储的 docId
        this.docId = docId; // 存储到组件的数据中

        const requestData = {
          orderDate: orderDate,
          userId: user.userId,
          hpId: hpId,
          smId: smId,
          docId: docId  // 添加 docId 到请求数据中
        };

        const response = await axios.post("http://localhost:8080/confirmorder/order", requestData);
        const data = response.data;

        this.userData = data.user;
        this.hospitalData = data.hospital;
        this.setmeal = data.setmeal;
        this.formattedBirthday = new Date(data.user.birthday).toLocaleDateString();
        this.orderDate = data.date;

        await this.createOrderAndFetchId();

      } catch (error) {
        console.error('调用失败', error);
        alert('调用失败，请稍后重试。');
      }
    },

    async createOrderAndFetchId() {
      try {
        const orderDate = getSessionStorage('selectedDate');
        const user = getSessionStorage('user');
        const hpId = getSessionStorage('selectedHospitalId');
        const smId = getSessionStorage('selectedSetmealId');
        const docId = this.docId; // 使用组件数据中存储的 docId

        const requestData = {
          orderDate: orderDate,
          userId: user.userId,
          hpId: hpId,
          smId: smId,
          docId: docId  // 添加 docId 到请求数据中
        };

        const response = await axios.post("http://localhost:8080/confirmorder/create", requestData);
        const responseData = response.data;
        if (responseData.code === 200) {
          this.orderId = responseData.orderId;
        } else {
          console.error('创建订单失败:', responseData.msg);
          alert('创建订单失败，请稍后重试。');
        }
      } catch (error) {
        console.error('创建订单失败:', error);
        alert('创建订单失败，请稍后重试。');
      }
    },

    async payWithOrderId() {
      if (!this.orderId) {
        console.error('订单ID为空，无法支付。');
        alert('订单ID为空，无法支付，请稍后重试。');
        return;
      }
      const encodedOrderId = encodeURIComponent(this.orderId);
      try {
        const res = await axios.get(`http://localhost:8080/pay/alipay?orderId=${encodedOrderId}`);
        const form = res.data;
        this.$refs.alipayForm.innerHTML = form;
        document.forms[0].submit();
      } catch (err) {
        console.error('获取支付表单失败:', err);
        alert('获取支付表单失败，请稍后重试。');
      }
    },
    
    listenForPaymentSuccess() {
      window.addEventListener('message', event => {
        const message = event.data;
        if (message && message.code === 200) {
          this.$router.push('/appointmentsuccess');
        } else {
          this.$router.push('/appointmentfail');
        }
      });
    }
  }
};
</script>



<style scoped>
/*********************** 总容器 ***********************/
.wrapper {
  width: 100%;
  height: 100%;
  background-color: #F9F9F9;
}

/*********************** header ***********************/
header li {
  list-style-type: none;
}

.icon {
  float: left;

  width: 80%;
  height: 8.2vw;
}



header {
  width: 100%;
  height: 15.7vw;
  background-color: #FFF;

  position: fixed;
  left: 0;
  top: 0;

  display: flex;
  align-items: center;
  justify-content: space-between;

  box-sizing: border-box;
  padding: 0 3.6vw;
}

header .fa {
  font-size: 8vw;
}

/*********************** footer ***********************/
footer {
  width: 100%;
  height: 14.2vw;
  box-sizing: border-box;
  border-top: solid 1px #E9E9E9;
  background-color: #FFF;

  position: fixed;
  left: 0;
  bottom: 0;
}

footer ul {
  width: 100%;
  height: 14.2vw;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

footer ul li {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  font-size: 3vw;
  color: #999;

  user-select: none;
  cursor: pointer;
}

footer ul li .fa {
  font-size: 5vw;
}

/*********************** common样式 ***********************/
.top-ban {
  width: 100%;
  height: 15.7vw;
}

.bottom-ban {
  width: 100%;
  height: 26.2vw;
}

/*********************** section ***********************/
section {
  width: 86vw;
  margin: 0 auto;
}

section .title {
  width: 100%;
  height: 12vw;
  border-bottom: solid 1px #EEE;

  display: flex;
  align-items: center;
}

section .title p {
  height: 3.4vw;
  line-height: 3.4vw;
  font-size: 4.2vw;
  font-weight: 600;
  box-sizing: border-box;
  padding-left: 3vw;
  border-left: solid 2px #127A90;
}

section table {
  font-size: 3.6vw;
  color: #555;
  margin-top: 2vw;
}

section table tr {
  line-height: 8vw;
}

section table tr td:first-child {
  width: 22%;
}

/*********************** bottom-btn ***********************/
.bottom-btn {
  width: 100%;
  height: 12vw;
  background-color: #FFF;

  position: fixed;
  left: 0;
  bottom: 14.2vw;

  display: flex;
}

.bottom-btn .first {
  flex: 2;
  line-height: 12vw;
  font-size: 4.6vw;
  box-sizing: border-box;
  padding-left: 6vw;
}

.bottom-btn .first span {
  color: #F77B2D;
}

.bottom-btn .last {
  flex: 1;
  background-color: #117C94;
  line-height: 12vw;
  text-align: center;
  font-size: 5vw;
  color: #FFF;

  user-select: none;
  cursor: pointer;
}
</style>